package com.moyun.syssecurity.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @return
 * @Author yangboxuan
 * @Description 处理凭证无效的情况
 * @Date 2021/5/26 11:14
 * @Param
 **/
@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.warn("进入到认证入口,拦截的URL路径为-->" + request.getRequestURI());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 响应方式1
//         输出失败的原因  401 认证失败
//                    out.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");
//        out.write("{\"code\":\"401\",\"msg\":\"" + errorMsg + "\"}");
//         这里我们不使用字符串拼接的方式返回json格式的数据  可以自定义发送内容 登录失败后信息会被封装到AutehnticationException类中，返回信息即可

        // 响应方式2  response.sendError 方式会使我们自定义的返回数据失效
//        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"凭证无效");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter out = response.getWriter();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        map.put("msg", getErrorMsg(e));
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();
    }

    // 获取登录异常具体信息
    public String getErrorMsg(Exception exception) {
        String error = "";
        if (exception instanceof LockedException) {
            error = "账户已锁定";
        } else if (exception instanceof AccountExpiredException) {
            error = "账户已过期";
        } else if (exception instanceof CredentialsExpiredException) {
            error = "证书已过期";
        } else if (exception instanceof InsufficientAuthenticationException) {
            error = "请先进行登录";
        } else {
            // 不是系统定义异常，是我们自定义的异常. 例如我们自定义的验证码校验失败的异常
            error = exception.getMessage();
        }
        return error;
    }
}
